import React, { Component } from "react";
import { connect } from "react-redux";

const mapStateToProps = (state) => {
  return {
    list: state.get("list"),
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    push(name) {
      dispatch({ type: "push", payload: { id: new Date().getTime(), name } });
    },
    remove(id) {
      dispatch({ type: "remove", id });
    },
  };
};

@connect(mapStateToProps, mapDispatchToProps)
class Todolist extends Component {
  state = {
    value: "",
  };

  handleChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  };

  fn = () => {
    this.props.push(this.state.value);
    this.setState({
      value: "",
    });
  };

  fn2 = (id) => {
    this.props.remove(id);
  };

  render() {
    return (
      <>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
        />
        <button onClick={this.fn}>添加</button>

        <ul>
          {this.props.list.map((item) => (
            <li key={item.id}>
              {item.name} -{" "}
              <button onClick={() => this.fn2(item.id)}>删除</button>
            </li>
          ))}
        </ul>
      </>
    );
  }
}

export default Todolist;
